<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2019/7/19
 * Time: 下午2:05
 */

namespace App\Http\Model;


use Illuminate\Support\Facades\Redis;


class RoomTally
{
    private $redisRoomTallyMap = "ROOM:TALLY:"; //ROOM:TALLY::{room_id}
    private $redisRoomTallyParam = "ROOM:TALLY:PARAM:"; //ROOM:TALLY:PARAM:{room_id}
    private $redisRoomTallySendZset = "ROOM:TALLY:SEND"; //ROOM:TALLY:SEND:{room_id}

    /**
     * 累加礼物价值计数
     * @param $roomId
     * @param $microId
     * @param $val
     * @return int
     */
    public function inc($roomId, $userId, $val)
    {
        $key = $this->redisRoomTallyMap . $roomId;
        $incVal = Redis::HINCRBY($key, $userId, $val);
        return intval($incVal);
    }

    /**
     * 关闭计数
     * @param $roomId
     * @return mixed
     */
    public function close($roomId)
    {
        $key = $this->redisRoomTallyMap . $roomId;
        Redis::DEL($key);
        $key = $this->redisRoomTallySendZset . $roomId;
        Redis::DEL($key);
        $key = $this->redisRoomTallyParam . $roomId;
        return Redis::DEL($key);
    }


    /**
     * 开启计数
     * @return mixed
     */
    public function open($roomId)
    {
        $key = $this->redisRoomTallyParam . $roomId;
        return Redis::HSET($key, 'opened', 1);
    }


    /**
     * 获取当前开启状态
     * @param $roomId
     * @return int
     */
    public function opened($roomId)
    {
        $key = $this->redisRoomTallyParam . $roomId;
        $ret = Redis::HGET($key, 'opened');
        if (empty($ret)){
            return 0;
        }
        return intval($ret);
    }


    /**
     * 获取所有麦数据
     * @param $roomId
     * @return array
     */
    public function getValues($roomId){
        $retData = [];
        $key = $this->redisRoomTallyMap . $roomId;
        $retArr = Redis::HGETALL($key);
        foreach ($retArr as $k => $v){
            $retData[] = ['user_id' => $k, 'val' => $v];
        }
        return $retData;
    }

    /**
     * 设置用户房间计数
     */
    public function setUserTally($roomId, $userId, $val)
    {
        $key = $this->redisRoomTallyMap . $roomId;
        $res = Redis::HSET($key, $userId, $val);
        return $res;
    }

}